package com.adinnet.api.product.controller;


import com.adinnet.api.classs.model.vo.ClasssResp;
import com.adinnet.api.product.model.vo.ProductDetailsResp;
import com.adinnet.api.product.model.vo.ProductResp;
import com.adinnet.api.product.service.ProductService;
import com.adinnet.core.JsonResult;
import com.adinnet.core.PageResp;
import com.adinnet.core.exception.BizException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * <p>
 * 商品表 前端控制器
 * </p>
 *
 * @author zYshuai
 * @since 2020-12-03
 */
@RestController
@RequestMapping("/api/product")
public class ProductController {


    @Autowired
    private ProductService productService;

    /**
     * 商品列表
     *
     * @return
     */
    @GetMapping("list")
    public PageResp productList(Integer limit, Integer page, HttpServletRequest request, HttpServletResponse response) {
        try {
            if (null == limit) {
                return new PageResp("limit不能为空");
            }
            if (null == page) {
                return new PageResp("page不能为空");
            }
            Page<ProductResp> productList = productService.productList(limit, page);
            if (null==productList||CollectionUtils.isEmpty(productList.getRecords())) {
                return new PageResp(Lists.newArrayList());
            }
            return new PageResp(productList.getRecords(), productList.getTotal());
        } catch (BizException e) {
            return new PageResp(e.getMessage());
        } catch (Exception e) {
            return new PageResp("查询商品列表失败!");
        }
    }

    /**
     * 商品详情
     *
     * @return
     */
    @GetMapping("list/details")
    public JsonResult productDetails(Integer productId, HttpServletRequest request, HttpServletResponse response) {
        try {
            if (null == productId) {
                return JsonResult.error("productId不能为空");
            }
            ProductDetailsResp productDetails = productService.productDetails(productId);
            if (null == productDetails) {
                return JsonResult.ok().put("data", new JSONObject());
            }
            return JsonResult.ok().put("data", productDetails);
        } catch (BizException e) {
            return JsonResult.error(e.getMessage());
        } catch (Exception e) {
            return JsonResult.error("查询商品详情失败!");
        }
    }
}
